<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/21
 * Time: 下午3:31
 */

namespace frontend\controllers;


use common\helpers\AjaxHelper;
use common\models\Check;
use common\models\Order;
use common\models\search\OrderSearch;
use common\models\search\VipOrderForm;
use common\models\User;
use common\models\UserCase;
use common\models\UserConsignee;
use frontend\models\CheckForm;
use frontend\models\search\PackageSearch;
use Yii;
use common\core\Controller;
use yii\filters\AccessControl;
use yii\helpers\Url;

class MemberController extends BaseController{
    
    public function behaviors(){
        return [
            'access' => [
                'class' => AccessControl::className(),
//                'only' => ['login', 'logout', 'signup'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    
                ],
                'denyCallback' => function(){
                    Yii::$app->response->redirect(Url::toRoute(['site/index']))->send();
                }
            ],
        ];
    }
    
    /**
     * 首页
     * @return string
     */
    public function actionIndex(){
    
        return $this->render('index');
    }
    
    public function actionUserInfo()
    {
        return $this->render('user-info');
    }
    
    
    /**
     * 基本信息
     */
    public function actionInfo()
    {
        if( Yii::$app->request->isPost ){
            $model = Yii::$app->user->identity;
            $model->scenario = User::SCENARIO_COMPLETE;
            $model->attributes = Yii::$app->request->getBodyParams();
            $response = new AjaxHelper;
            if( $model->validate() && $model->save() ){
                $response->data = '保存成功';
            }else{
                $response->msg = $model->getOneErrors();
            }
            return $response;
        }
        return $this->render('info', ['info' => Yii::$app->user->identity]);
    }
    
    /**
     * 个人病史
     * @return AjaxHelper|string
     */
    public function actionCase()
    {
        if( Yii::$app->request->isPost ){
            $model = Yii::$app->user->identity->userCase ?: new UserCase();
            $model->user_id = $model->user_id ?: Yii::$app->user->id;
            $model->attributes = Yii::$app->request->post();
            $response = new AjaxHelper;
            if( $model->validate() && $model->save() ){
                $response->data = '保存成功';
            }else{
                $response->msg = $model->getOneErrors();
            }
            return $response;
        }
        return $this->render('case', ['info' => Yii::$app->user->identity->userCase]);
    }
    
    
/**
     * 个人病史
     * @return AjaxHelper|string
     */
    public function actionConsignee()
    {
        if( Yii::$app->request->isPost ){
            $model = Yii::$app->user->identity->consignee ?: new UserConsignee();
            $model->user_id = $model->user_id ?: Yii::$app->user->id;
            $model->attributes = Yii::$app->request->post();
            $response = new AjaxHelper;
            if( $model->validate() && $model->save() ){
                $response->data = '保存成功';
            }else{
                $response->msg = $model->getOneErrors();
            }
            return $response;
        }
        return $this->render('consignee', ['info' => Yii::$app->user->identity->consignee]);
    }
    /**
     * 购买会员申请
     */
    public function actionShenqing($type)
    {
        if( Yii::$app->wechat->isWechat ){
            $js = Yii::$app->wechat->getApp()->js;
            $config = $js->config(array('chooseImage', 'previewImage', 'uploadImage'));
        }
        return $this->render('shenqing', [
            'wxConfig' => $config,
            'type'     => $type
        ]);
    }
    
    public function actionSaveShenqing()
    {
        if( Yii::$app->request->isAjax ){
            $ids = Yii::$app->request->getBodyParam('ids');
            $model = new CheckForm([
                'user_id' => Yii::$app->user->id,
                'bl_img' => implode(',', $ids),
                'type'   => Yii::$app->request->getBodyParam('type'),
                'remark'   => Yii::$app->request->getBodyParam('remark'),
            ]);
            $result = $model->submit();
            $response = new AjaxHelper;
            if( $result ){
                $response->data = $result;
            }else{
                $response->msg =  $model->getOneErrors();
            }
            return $response;
        }
    }
    
    public function actionVipBuy()
    {
        // 查询可购买的会员卡
        $package = new PackageSearch;
        $list = $package->getPackageList();
        return $this->render('vip-buy', ['list' => $list]);
    }
    
    public function actionDoBuy()
    {
        $package_id = Yii::$app->request->getBodyParam('package_id');
        
        $model = new VipOrderForm(['package_id' => $package_id, 'user_id' => Yii::$app->user->id]);
        
        $response = new AjaxHelper();
        
        if( $model->order() ){
            $payment = Yii::$app->wechat->app->payment;
            $wechatOrder = new Order([
                'openid' => Yii::$app->user->identity->wechat_id,
                'body' => '购买'. $model->getPackage()->package_name,
                'out_trade_no' => $model->getOrder()->order_sn,
                'total_fee' => $model->getOrder()->money * 100,
                'trade_type' => "JSAPI",
                'notify_url' => Yii::$app->request->getHostInfo(). '/vip-buy.php',
            ]);
            $result = $payment->prepare($wechatOrder);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId, false);
                $response->data = $json;
            }else{
                $response->msg = '支付失败';
            }
        
        }else{
            $response->msg = $model->getOrder()->getErrors();
        }
        return $response;
        
    }
    
    /**
     * 我的订单
     */
    public function actionOrder()
    {
        $model = new OrderSearch();
        $dataProvider = $model->search(['user_id' => Yii::$app->user->id]);
        return $this->render('order', ['list' => $dataProvider->getModels()]);
    }
    
    public function actionOrderInfo($id)
    {
        $model = Order::findById($id);
        return $this->render('order-info', ['model' => $model]);
    }
    
    /**
     * 购买申请
     */
    public function actionCheck($type)
    {
        $model = Check::findAll(['user_id' => Yii::$app->user->id, 'type' => $type]);
        return $this->render('buy' , ['list' => $model, 'type' => $type]);
    }
    
    public function actionBuyInfo($id)
    {
        $model = Check::findOne(['id' => $id]);
        // 微信端处理
        if( Yii::$app->wechat->isWechat ){
            $js = Yii::$app->wechat->getApp()->js;
            $config = $js->config(array('previewImage'));
        }
        return $this->render('buy-info', ['model' => $model, 'wxConfig' => $config]);
    }
    
    
}